package com.affablebeans.model.dal;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.affablebeans.model.entity.GenericEntity;

/**
 *
 * @author Bora SAYINER
 * @since Jan 25, 2015 6:36:04 PM
 * @version 1.0
 */
public abstract class AbstractDAL<E extends GenericEntity> implements GenericDAL<E> {

	private final DataSource dataSource;
	private final String tableName;

	public AbstractDAL(DataSource dataSource, String tableName) {
		this.dataSource = dataSource;
		this.tableName = tableName;
	}

	Connection createConnection() throws SQLException {
		return dataSource.getConnection();
	}

	@Override
	public int getCount() throws SQLException {
		int count = 0;
		try (Connection connection = createConnection()) {
			try (Statement statement = connection.createStatement()) {
				ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) AS 'count' FROM " + tableName);
				if (resultSet.next()) count = resultSet.getInt("count");

			}
		}
		return count;
	}

	abstract E createEntity(ResultSet resultSet) throws SQLException;

	Date convertToDate(java.util.Date date) {
		return new Date(date.getTime());
	}

}
